package com.situ.onlinebookstore.back.controller;

import com.situ.onlinebookstore.back.service.CategoryService;
import com.situ.onlinebookstore.common.entity.Category;
import com.situ.onlinebookstore.common.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
public class CategoryController {
    private final CategoryService categoryService;
    //添加
    @RequestMapping("/add")
    public Result add(Category category){
        //1- 参数
        try {
            //2- 校验
            if (category.getName() == null || category.getName().length() == 0 || category.getName().length()>32){
                throw new Exception("分类名必须是长度1~32位的字符串！");
            }
            //3- 逻辑处理
            categoryService.add(category);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //修改
    @RequestMapping("/edit")
    public Result edit(Category category){
        //1- 参数
        try {
            //2- 校验
            if (category.getName() == null || category.getName().isEmpty() || category.getName().length()>32){
                throw new Exception("分类名必须是长度1~32位的字符串！");
            }
            //3- 逻辑处理
            categoryService.edit(category);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/update")
    public Result update(Category category){
        //1- 参数
        try {
            //2- 校验

            //3- 逻辑处理
            categoryService.edit(category);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //查询
    @RequestMapping("search")
    public Result search(Integer page,Integer limit, Category category){
        if (page == null){
            return Result.ok(categoryService.search(category));
        }else {
            return Result.ok(categoryService.searchByPage(page,limit,category));
        }

    }
}
